package com.jmp.security;

import com.jmp.security.base.ClientDetail;
import com.jmp.security.base.RequestDetail;
import com.jmp.security.base.TokenEntityService;
import com.jmp.security.base.UserDetail;
import lombok.extern.slf4j.Slf4j;
import one.stand.entity.TokenEntity;
import one.stand.enums.LoginEnum;
import one.stand.model.User;
import one.stand.service.user.TokenService;

import java.util.Objects;

@Slf4j
public class TokenEntityServiceImpl implements TokenEntityService {

    private TokenService tokenService;

    public TokenEntityServiceImpl(TokenService tokenService) {
        this.tokenService = tokenService;
    }

    @Override
    public TokenEntity create(RequestDetail requestDetail, ClientDetail clientDetail, UserDetail userDetail) {
        User userModel = userDetail.getUserModel();
        LoginEnum loginEnum = requestDetail.getLoginEnum();

        TokenEntity tokenModel = new TokenEntity();
        tokenModel.setLoginProgramName(loginEnum.getCode());
        if (Objects.nonNull(clientDetail)) {
            tokenModel.setCompanyKey(clientDetail.getCompanyKey());
        }
        tokenModel.setEquCode(requestDetail.getEquCode());

        tokenModel.setId(Long.valueOf(userModel.getUserId()));
        tokenModel.setRoleId(userModel.getRoleId());
        tokenModel.setSessionKey(userDetail.getSessionKey());
        if (userDetail.getCardModel() != null) {
            tokenModel.setCId(userDetail.getCardModel().getCompanyId().longValue());
            tokenModel.setMyCardId(userDetail.getCardModel().getCardId());
        } else if (userModel.getRoleId() != null && userModel.getRoleId() > 0) {
            tokenModel.setCId(userModel.getRoleId().longValue());
        }

        if (loginEnum.isLoginSingle()) {//单点登录时清除旧的Token
            tokenService.remove(tokenModel.getId().intValue(), loginEnum);
        }

        //登录
        tokenService.save(tokenModel);

        return tokenModel;
    }
}
